import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';

import { Request } from 'express';
import { checkAuthorization } from 'my-node-core/security';

import { SecurityRequestMapQueryService } from '@modules/auth/services/security-request-map-query.service';
import { UserActiveTokenManagerService } from '@modules/auth/services/user-active-token-manager.service';

@Injectable()
export class JwtAuthGuard implements CanActivate {
  constructor(
    private readonly securityRequestMapQueryService: SecurityRequestMapQueryService,
    private readonly userActiveTokenManagerService: UserActiveTokenManagerService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest<Request>();
    const prefix = Reflect.get(global, 'nest:global_prefix');
    const method = request.method;
    const url = request.url.replace(prefix, '');
    const authHeader = request.headers.authorization || '';

    const granted = await checkAuthorization(
      request.method,
      url,
      authHeader,
      this.userActiveTokenManagerService,
      this.securityRequestMapQueryService,
    );

    // if (!granted) {
    //   throw new UnauthorizedException('Missing authentication token');
    // }

    return true;
  }
}
